<template>
	<view class="room-page-con f30">
		<view :style="{ top: safeAreaInsetTop + 'px' }" @click="goBack" class="back-btn">
			<uni-icons class="back-icon" type="left" size="20"></uni-icons>
		</view>
		<view v-if="formData.images.length > 0" class="swiper-con">
			<swiper class="swiper" @change="changeImg" circular autoplay>
				<swiper-item v-for="(item, index) in formData.images" :key="index">
					<van-image width="100%" height="580rpx" fit="cover" :lazy-load="true" :src="item.image_url" />
				</swiper-item>
			</swiper>
			<div class="my-swiper-current">
				{{ current + 1 }}/{{ formData.images.length }}
			</div>
		</view>
		<view class="swiper-con" v-else>
			<van-image width="100%" height="580rpx" fit="cover" />
		</view>
		<view class="page-content">
			<view class="home-name-con">
				<view class="name">{{ formData.name || "无房源名称" }}</view>
				<view class="tag-list-con">
					<span class="tag-code">#{{ formData.id }}</span>
					<span class="tag-item" v-for="(item, index) in formData.characterTag" :key="index">
						{{ item.tag_name }}
					</span>
				</view>
				<view class="home-des">
					{{ formData.houseTagString || "无数据" }}

				</view>
			</view>
			<view class="room-select-con">
				<view class="select-date-con">
					<view @click="goSelectDate" v-if="!selectDate">选择日期
						<uni-icons class="my-right-icon" type="right" size="18"></uni-icons>
					</view>
					<view class="flex-between" v-else>
						<view>
							{{ selectDate.startDate }}
							<span class="f24 ml10">入住</span>
						</view>
						<view>
							{{ selectDate.endDate }}
							<span class="f24 ml10">离开</span>
						</view>
						<view @click="goSelectDate" class="f24">
							共 {{ selectDate.totalDays }} 晚
							<uni-icons v-if="pageType == 1" class="my-right-icon" type="right" size="12"></uni-icons>
						</view>
					</view>
				</view>
				<view class="room-list-con">
					<view  v-for="(item, index) in formData.rooms" :key="index"
						class="room-item">
						<view class="room-img-con">
							<van-image width="193rpx" height="140rpx" fit="cover" :src="item.image_urls[0]" />
						</view>

						<view class="room-name-con">
							<view class="room-name">
								{{ item.name || "无房间名称" }}
								<uni-icons class="my-right-icon" type="right" size="18"></uni-icons>
							</view>
							<view class="room-info oellipsis">{{ item.bedNameString }} </view>
							<view class="room-price">{{ item.price_public || "0" }}加元/晚 </view>
							<view @click="goRoomInfo(item)" v-if="pageType == 1 && userInfo.role != 2" :class="{ 'disable-btn': item.disableBtn }" class="room-btn">
								{{ item.disableBtn ? "不可预订" : "预订" }}
							</view>
							<view @click="editDate(item)" v-if="userInfo.role == 2"  class="room-btn">
								修改可租日期
							</view>
							
						</view>
					</view>
				</view>
			</view>

			<view class="introduction"> 房源介绍 </view>
			<view :style="{ height: formData.descriptionShowAll ? 'auto' : '136rpx' }"
				:class="{ oellipsis4: !formData.descriptionShowAll }" class="f30 description">
				{{ formData.description || "无房源信息" }}
			</view>
			<view @click="changeHeight('descriptionShowAll')"
				v-if="formData.descriptionShowMore" class="show-more">
				{{ formData.descriptionShowAll ? "收起" : "显示更多" }}
			</view>

			<view class="room-map">
				<view class="map">
					<img src="https://vihome.s3.ca-central-1.amazonaws.com/mini-app-static/location.png" alt="" />
				</view>
				<view class="map-tips">准确地址将在支付后提供</view>
			</view>
			<view class="nearby-con">
				<view v-for="(item, index) in nearByData" :key="index" class="nearby-item">
					<span> {{ item.name }} </span>
					<span> {{ item.distance }}</span>
				</view>
			</view>
			<view @click="changeNearbyData" v-if="nearByDataShowMore" class="show-more">
				{{ nearByDataShowAll ? "收起" : "显示更多" }}
			</view>

			<view class="introduction"> 设施服务 </view>
			<view class="service-con">
				<view v-for="(item, index) in formData.deviceTag" :key="index" class="service-item">
					{{ item.tag_name }}
				</view>
			</view>
			<view @click="changeTagShow" v-if="formData.deviceTagShowMore" class="show-more">
				<span v-if="!formData.deviceTagShowAll">
					显示所有{{ formData.deviceTagAll.length }}项
				</span>
				<span v-else> 收起 </span>
			</view>

			<view class="introduction"> 管家介绍 </view>
			<view class="landlady">
				<view class="landlady-img">
					<van-image width="109rpx" height="109rpx" fit="cover" :src="formData.landlord.avatar_url" />
				</view>
				<view class="landlady-content">
					<view class="f30 font-weight">{{
            formData.landlord.nickname || "无管家名字"
          }}</view>
					<view :class="{ oellipsis2: !formData.landlordShowAll }"
						:style="{ height: formData.landlordShowAll ? 'auto' : '75rpx' }" class="f28">
						{{ formData.landlord_desc || "无管家介绍信息" }}
					</view>
				</view>
			</view>
			<view @click="changeHeight('landlordShowAll') " v-if="formData.landlordShowMore"
				class="show-more">
				{{ formData.landlordShowAll ? "收起" : "显示更多" }}
			</view>

			<notice v-if="pageInitFlag"></notice>
		</view>
		<view v-if="userInfo.role == 2" class="house-info-foot">
			<view @click="deactive" v-if="formData.status == 2" class="btn down-btn">下 架</view>
			<view @click="editHouse" v-if="formData.status != 1" class="btn">编 辑</view>
			<view v-if="formData.status == 1" class="btn not-edit">审核中不可编辑</view>
		</view>
		<view v-if="pageType == 1 && userInfo.role != 2" class="house-info-foot center-all">
			<view @click="showerweima" class="contact-btn btn">联系ViHome管家</view>
			<view @click="isGoRoomInfo" class="btn down-btn"> 预 订 </view>
		</view>
		<van-dialog confirm-button-class="color-orange" id="van-dialog" />

		<erweima :erweimaUrl="formData.landlord.qr_code_url"  ref="erweimaRef">
			<template v-slot:headerTips>
				<view class="grey-tips">微信二维码</view>
			</template>
			<template v-slot:footTips>
				<view class="mb20">长按二维码添加管家微信</view>
			</template>
		</erweima>
	</view>
</template>

<script>
	import Dialog from "wxcomponents/vant/dialog/dialog";
	import notice from "@/components/notice.vue";
	import erweima from 'pages/ownr/erweima.vue'

	export default {
		components: {
			notice,
			erweima
		},
		data() {
			return {
				pageType: 1, // 1 详情 2快照
				houseId: "",
				userInfo: this.$getStorage("userInfo"),
				selectDate: this.$getStorage("selectDate"),
				formData: {
					images: [],
					name: "",
				},
				current: 0,
				safeAreaInsetTop: 0,
				nearByData: [],
				nearByAllData: [],
				nearByDataShowMore: false,
				nearByDataShowAll: false,
				snapshot: "",
				pageInitFlag: false,
			};
		},
		onLoad(option) {
			this.pageType = option.pageType || 1;
			if (option.houseId) {
				this.houseId = option.houseId;
				this.$setStorage("houseId", this.houseId);
			} else {
				this.houseId = this.$getStorage("houseId");
			}
		},
		// onShow() {
		// 	// 页面显示时监听事件
		// 	clearTimeout(this.timer);
		// 	this.timer = setTimeout(()=>{
		// 		uni.$on('refreshHouseData', this.init);
		// 	},500)
			
		// },
		// onHide() {
		// 	// 页面隐藏时移除监听
		// 	uni.$off('refreshHouseData', this.init);
		// },
		mounted() {
			this.getTopHeight();
		},
		onShow() {
			this.init();
		},
		methods: {
			init() {
				if (this.pageType == 1) {
					this.getMyHouseInfo();
				} else {
					this.snapshot = this.$getStorage("snapshot");
					this.formData = this.snapshot.info;
					this.handData();
					this.formData.latitude && this.getNearby();
				}
			},
			getRentDate() {
				this.selectDate = this.$getStorage("selectDate");
				this.formData.rooms.forEach((item, index, arr) => {
					arr[index]["days"] = this.formData.days;
					arr[index]["price_public"] = this.$formatNumber(item.price_public);
					arr[index]["deposit"] = this.$formatNumber(item.deposit);

					let data = {
						house_id: item.house_id,
						room_id: item.id,
					};
					this.$http.getRentDate(data).then((res) => {
						let list = [];
						res.forEach((item) => {
							let date1 = new Date(item[0].replace(/-/g, "/")).getTime();
							let date2 = new Date(item[1].replace(/-/g, "/")).getTime();
							let days = this.daysBetween(date1, date2);
							list.push(item[0]);
							let tamp = date1;
							for (let i = 0; i < days; i++) {
								tamp += 1000 * 24 * 60 * 60;
								list.push(this.$timestampToTime(tamp));
							}
						});
						arr[index]["rentDate"] = list || [];
						if (this.selectDate && this.selectDate.startTime) {
							if (
								this.daysBetween(
									this.selectDate.startTime,
									this.selectDate.endTime
								) < this.formData.days
							) {
								arr[index]["disableBtn"] = true;
							} else {
								let disabledDate = [...item.disabled_date_range, ...list];
								arr[index]["disableBtn"] = disabledDate.some((i) => {
									return (
										i > this.selectDate.beginDate && i < this.selectDate
										.overDate
									);
								});
							}
						}
					});
				});
			},
			daysBetween(date1, date2) {
				const oneDay = 24 * 60 * 60 * 1000; // 一天的毫秒数
				// let days = Math.round(Math.abs((date1 - date2) / oneDay)) - 1;
				return Math.round(Math.abs((date1 - date2) / oneDay));
			},
			setRoomStatus() {
				this.selectDate = this.$getStorage("selectDate");
				this.formData.rooms.map((item) => {
					item["disableBtn"] = item.disabled_date_range.some((i) => {
						return i > this.selectDate.beginDate && i < this.selectDate.overDate;
					});
				});
			},
			getMyHouseInfo() {
				let name = "getHouseInfo";
				if (this.$isLogin() && this.userInfo.role == 2) {
					name = "getMyHouseInfo";
				}

				this.$http[name](this.houseId).then((res) => {
					this.formData = res;
					this.handData();
					this.formData.latitude && this.getNearby();
					if (!this.userInfo || this.userInfo.role == 1) {
						this.getRentDate();
					}
				});
			},
			handData() {
				let houseTagString = "";
				houseTagString = `${this.formData.house_type} | ${
        this.formData.bedrooms
      }室  ${this.formData.livingrooms}厅 ${this.formData.kitchens}厨  ${
        this.formData.bathrooms
      }卫 |  ${(this.formData.area / 9).toFixed(2)}m² | ${
        this.formData.cooking ? "可做饭" : "不可做饭"
      }`;
				this.formData.houseTagString = houseTagString;
				let characterTag = [];
				let deviceTag = [];
				this.formData.tags.forEach((item) => {
					if (item.type == 2) {
						characterTag.push(item);
					} else {
						deviceTag.push(item);
					}
				});
				if (characterTag.length == 0) {
					characterTag = [{
						tag_name: "无房源特色标签",
					}, ];
				}
				if (deviceTag.length == 0) {
					deviceTag = [{
						tag_name: "无设施服务标签",
					}, ];
				}
				this.formData.characterTag = characterTag;
				this.formData.deviceTagAll = deviceTag;
				this.formData.deviceTag = deviceTag;

				this.formData.rooms.map((item) => {
					item["bedNameString"] = "";
					if (item.beds.length > 0) {
						item["bedNameString"] = this.getBedNameString(item.beds);
					}
				});

				this.formData["descriptionShowAll"] = true;
				if (this.formData.description && this.formData.description.length > 80) {
					this.formData["descriptionShowMore"] = true;
					this.formData["descriptionShowAll"] = false;
				}
				this.formData["landlordShowAll"] = true;
				if (
					this.formData.landlord_desc.length &&
					this.formData.landlord_desc.length > 80
				) {
					this.formData["landlordShowMore"] = true;
					this.formData["landlordShowAll"] = false;
				}

				this.formData["deviceTagShowAll"] = true;
				if (
					this.formData.deviceTagAll &&
					this.formData.deviceTagAll.length > 10
				) {
					this.formData["deviceTagShowMore"] = true;
					this.formData["deviceTagShowAll"] = false;
					this.formData.deviceTag10 = this.formData.deviceTagAll.slice(0, 10);
					this.formData.deviceTag = this.formData.deviceTag10;
				}
				this.$setStorage("houseInfo", this.formData);
				this.pageInitFlag = true;
			},
			showerweima() {
				this.$refs.erweimaRef.show();
			},
			getNearby() {
				let data = {
					lat: this.formData.latitude,
					lng: this.formData.longitude,
					radius: 500,
				};
				this.$http.getNearby(data).then((res) => {
					res.map((item) => {
						if (item.distance < 1) {
							item.distance = Math.floor(item.distance * 1000) + "m";
						} else {
							item.distance = item.distance + "km";
						}
					});

					this.nearByAllData = res;
					if (res.length > 4) {
						this.nearByDataShowMore = true;
						this.nearByData = res.slice(0, 4);
					}
				});
			},
			changeNearbyData() {
				if (this.nearByDataShowAll) {
					this.nearByDataShowAll = false;
					this.nearByData = this.nearByAllData.slice(0, 4);
				} else {
					this.nearByDataShowAll = true;
					this.nearByData = this.nearByAllData;
				}
			},
			getTopHeight() {
				const result = uni.getSystemInfoSync();
				this.safeAreaInsetTop = result.safeArea.top;
			},
			changeImg(e) {
				this.current = e.detail.current;
			},
			changeHeight(name) {
				this.formData[name] = !this.formData[name];
				this.$forceUpdate()
				
			},
			changeTagShow() {
				if (this.formData.deviceTagShowAll) {
					this.formData.deviceTagShowAll = false;
					this.formData.deviceTag = this.formData.deviceTag10;
				} else {
					this.formData.deviceTagShowAll = true;
					this.formData.deviceTag = this.formData.deviceTagAll;
				}
				this.$forceUpdate();
			},
			getBedNameString(beds) {
				// 按type属性分组并累加num值
				const groupedBeds = beds.reduce((acc, bed) => {
					const existingBed = acc.find((b) => b.type === bed.type);
					if (existingBed) {
						existingBed.num += bed.num;
					} else {
						acc.push({
							...bed
						});
					}
					return acc;
				}, []);

				// 生成新的数组，包含累加后的num和title
				const result = groupedBeds.map((bed) => ({
					totalNum: bed.num,
					title: bed.title,
				}));

				// 输出结果，并确保不重复
				const uniqueResults = Array.from(
					new Set(result.map((item) => `${item.totalNum}张${item.title}`))
				).join(",");
				return uniqueResults;
			},
			editDate(item) {
				console.log(11111)
				this.$setStorage("roomInfo", item);
				this.$goPage(1, `/subPublishHouse/setPrice/setHireDate?type=2`);
			},
			goSelectDate() {
				if (this.pageType == 2 || this.userInfo?.role == 2) {
					return;
				}
				this.$setStorage("roomInfo", "");
				this.$goPage(1, `/pages/date/selectDate`);
			},
			isGoRoomInfo() {
				if (this.formData.rooms.length > 1) {
					this.$toast("请选择您要预订的房间");
					return;
				}
				this.goRoomInfo(this.formData.rooms[0]);
			},
			goRoomInfo(item) {
				item["houseName"] = this.formData.name;
				item["check_in"] = this.formData.check_in;
				item["check_out"] = this.formData.check_out;
				item["landlord"] = this.formData.landlord;

				this.$setStorage("roomInfo", item);
				this.$goPage(1, `/subHouseDetail/roomDetail?pageType=${this.pageType}`);
			},
			deactive() {
				Dialog.confirm({
					title: "提示",
					message: "下架房源后再次上架，需经过审核。是否确定下架该房源?",
				}).then(() => {
					this.$http.deactive({
						id: formData.id
					}).then((res) => {
						this.formData.status = 0;
						this.$toast("下架成功");
					});
				});
			},
			editHouse() {
				if (this.formData.status != 2) {
					this.$setStorage("houseId", formData.id);
					this.$goPage(1, "/subPublishHouse/baseInfo/setHouseInfo");
					return;
				}
				Dialog.confirm({
					title: "提示",
					message: "是否确定编辑该房源?确定后系统将自动下架该房源。再次上架需经过审核。",
				}).then(() => {
					this.$http.deactive({
						id: this.formData.id
					}).then((res) => {
						this.formData.status = 0;
						this.$setStorage("houseId", this.formData.id);
						this.$goPage(1, "/subPublishHouse/baseInfo/setHouseInfo");
						// this.$toast('下架成功')
					});
				});
			},

			goBack() {
				uni.navigateBack({
					delta: 1,
					fail: () => {
						uni.switchTab({
							url: "/pages/index/index",
						});
					},
				});
			},
			nextStep() {
				// if(!this.formData.days) {
				//  this.$toast('请填写最少入住天数');
				// }
				this.$http.setHouseSubmit({
					id: this.houseId
				}).then((res) => {
					this.$goPage(1, "/subPublishHouse/resultTips");
					this.$setStorage("houseId", res.id);
					this.$toast("保存成功");
				});
			},
		},
	};
</script>

<style lang="scss" scoped>
	.room-page-con {
		width: 100%;
		font-size: 24rpx;
		color: #222222;
		padding-bottom: 200rpx;

		.swiper {
			width: 100%;
			height: 580rpx;
			box-sizing: border-box;
			position: relative;

			// background-color: #EC8403;
			.swiper-item {
				width: 100%;
				height: 580rpx;

				// position: relative ;
				.item-img {
					width: 100%;
					height: 100%;
				}
			}
		}

		::-webkit-scrollbar {
			display: none;
			width: 0;
			height: 0;
			color: transparent;
		}

		.page-content {
			position: relative;
			top: -36rpx;
			background-color: #fff;
			z-index: 9;
			border-radius: 30rpx 30rpx 0rpx 0rpx;
			padding: 0 36rpx;
		}

		.home-name-con {
			font-weight: 500;
			font-size: 30rpx;
			min-height: 96rpx;

			.name {
				line-height: 96rpx;
			}

			.tag-list-con {
				.tag-code {
					border: 1rpx solid #a7a7a7;
					border-radius: 4px 4px 4px 4px;
					padding: 0 8rpx;
					height: 35rpx;
					line-height: 35rpx;
					color: #a7a7a7;
					font-size: 24rpx;
					margin-right: 10rpx;
				}

				.tag-item {
					padding: 0 8rpx;
					height: 35rpx;
					line-height: 35rpx;
					background: #fff9f1;
					font-size: 24rpx;
					color: #ec8403;
					border-radius: 2rpx 2rpx 2rpx 2rpx;
					border: 1rpx solid #ffe3c0;
					margin-right: 10rpx;
					margin-top: 18rpx;
					white-space: nowrap;
				}
			}

			.home-des {
				font-size: 24rpx;
				color: #6e6e6e;
				margin: 15rpx 0 36rpx 0;

				.split-line {
					margin: 0 15rpx;
				}

				// .setBorder {
				// 	border-right: 1px solid #6E6E6E;
				// }
			}
		}

		.room-select-con {
			width: 678rpx;
			background: #ffffff;
			box-shadow: 0rpx 0rpx 12rpx 6rpx rgba(0, 0, 0, 0.05);
			border-radius: 12rpx 12rpx 12rpx 12rpx;
			margin: 36rpx auto;

			.select-date-con {
				width: 678rpx;
				height: 95rpx;
				line-height: 95rpx;
				background: #fce353;
				font-weight: bold;
				font-size: 30rpx;
				color: #222222;
				padding: 0 45rpx;
				box-sizing: border-box;
				vertical-align: middle;
			}

			.room-list-con {
				.room-item {
					padding: 50rpx 25rpx 50rpx 30rpx;
					display: flex;
					border-bottom: 1rpx solid #ebebeb;

					.room-img-con {
						width: 193rpx;
						height: 140rpx;
						border-radius: 7rpx 7rpx 7rpx 7rpx;
						border: 1rpx solid #ebebeb;
						margin-right: 20rpx;
					}

					.room-name-con {
						position: relative;
						width: 380rpx;

						.room-name {
							font-weight: bold;
							font-size: 30rpx;
							color: #383b43;
						}

						.room-info {
							font-size: 24rpx;
							color: #383b43;
							margin: 15rpx 0;
						}

						.room-price {
							font-weight: bold;
							font-size: 24rpx;
							color: #e33838;
						}

						.room-btn {
							position: absolute;
							bottom: 0;
							right: 0;
							// width: 103rpx;
							padding: 0 26rpx;
							height: 48rpx;
							font-size: 24rpx;
							line-height: 48rpx;
							background: #fce353;
							text-align: center;
							border-radius: 60rpx 60rpx 60rpx 60rpx;
						}
					}
				}
			}
		}

		.introduction {
			font-weight: bold;
			font-size: 43rpx;
			margin: 30rpx 0;
		}

		.description {
			overflow: hidden;
			padding-bottom: 20rpx;
		}

		.show-more {
			font-size: 30rpx;
			color: #eb9c38;
			text-align: center;
			margin: 36rpx 0;
		}

		.room-map {
			width: 678rpx;
			height: 348rpx;
			background: #ffffff;
			border-radius: 12rpx 12rpx 12rpx 12rpx;
			border: 1rpx solid #dadada;
		}

		.map {
			width: 677rpx;
			height: 292rpx;

			img {
				width: 100%;
				height: 100%;
			}
		}

		.map-tips {
			font-size: 24rpx;
			color: #717171;
			height: 56rpx;
			line-height: 56rpx;
			text-indent: 20rpx;
		}

		.nearby-con {
			margin-top: 36rpx;

			.nearby-item {
				display: flex;
				justify-content: space-between;
				font-size: 24rpx;
				color: #222222;
				padding: 0 20rpx;
				margin-bottom: 10rpx;

				span:nth-child(2) {
					color: #9d9d9d;
				}
			}
		}

		.service-con {
			.service-item {
				padding: 6rpx 12rpx;
				background: #ffffff;
				border-radius: 2rpx 2rpx 2rpx 2rpx;
				border: 1rpx solid #cecece;
				margin-right: 28rpx;
				margin-bottom: 28rpx;
				display: inline-block;
			}
		}

		.landlady {
			display: flex;

			.landlady-img {
				width: 109rpx;
				height: 109rpx;
				border-radius: 50%;
				margin-right: 20rpx;
				overflow: hidden;
			}

			.landlady-content {
				width: 510rpx;
			}
		}
	}

	.house-info-foot {
		width: 100%;
		height: 160rpx;
		background-color: #fff;
		padding: 22rpx 35rpx;
		box-sizing: border-box;
		position: fixed;
		bottom: 0;
		z-index: 9999999;
		display: flex;
		justify-content: center;
		align-items: center;
		box-shadow: 0rpx -3rpx 9rpx 3rpx rgba(0, 0, 0, 0.05);

		// padding-bottom: constant(safe-area-inset-bottom);
		// padding-bottom: env(safe-area-inset-bottom);
		.btn {
			width: 290rpx;
			height: 79rpx;
			line-height: 79rpx;
			background: #fff7ed;
			border-radius: 60rpx;
			text-align: center;
			font-size: 27rpx;
			color: #ec8403;
			margin: 0 5px;
		}

		.down-btn {
			background: #fce353;
			color: #222222;
		}

		.contact-btn {
			background: #E8E8E8;
			color: #222222;
		}

		.not-edit {
			background: #f1f1f1;
			color: #999999;
		}
	}

	.back-btn {
		position: fixed;
		// top:  50rpx;
		left: 30rpx;
		width: 70rpx;
		height: 70rpx;
		background: #ffffff;
		border-radius: 50%;
		z-index: 999999;

		// padding-top: constant(safe-area-inset-top);
		// padding-top: env(safe-area-inset-top);
		.back-icon {
			position: absolute;
			left: 50%;
			top: 50%;
			transform: translate(-50%, -50%);
		}
	}

	.swiper-con {
		position: relative;

		.my-swiper-current {
			position: absolute;
			bottom: 60rpx;
			right: 20rpx;
			height: 39rpx;
			line-height: 39rpx;
			background: rgba(0, 0, 0, 0.6);
			border-radius: 60rpx;
			padding: 0 10rpx;
			text-align: center;
			font-size: 24rpx;
			color: #ffffff;
			z-index: 999;
		}
	}
</style>